package nullby.omnia.activity.user;

import nullby.common.utils.CustomLog;
import nullby.omnia.ApplicationOmnia;
import nullby.omnia.R;
import nullby.omnia.activity.ActivityMain;
import nullby.omnia.db.DatabaseHelper;
import nullby.omnia.model.User;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ActivityAuthorization extends Activity implements OnClickListener {
	private static final String TAG = ActivityAuthorization.class
			.getSimpleName();

	private View vSplash;
	private Button bLogin;
	private Button bRegistration;

	private Boolean isLogin = true;

	private class AuthTask extends AsyncTask<Void, Void, User> {

		private Context context;
		private Handler handler;
		private Boolean isLogin;
		private String login;
		private String password;

		public AuthTask(final Context context, final String login,
				final String password) {
			super();
			this.context = context;
			this.handler = new Handler();
			this.isLogin = true;
			this.login = login;
			this.password = password;
		}

		@Override
		protected User doInBackground(Void... params) {
			return DatabaseHelper.get().auth(login, password);
		}

		@Override
		protected void onPostExecute(final User result) {
			super.onPostExecute(result);
			if (result.getId() != null) {
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						ApplicationOmnia.userId = result.getId();
						Intent intent = new Intent(ActivityAuthorization.this,
								ActivityMain.class);
						startActivity(intent);
						finish();
					}

				}, 2000);
			} else {
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						findViewById(R.id.vSplash).setVisibility(View.GONE);
					}

				}, 2000);

			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		CustomLog.logI(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_auth);

		initView();

		AuthTask authTask = new AuthTask(this, "admin", "admin");
		authTask.execute();
	}

	protected void initView() {
		vSplash = (View) findViewById(R.id.vSplash);
		bLogin = (Button) findViewById(R.id.bLogin);
		bRegistration = (Button) findViewById(R.id.bRegistration);

		bLogin.setOnClickListener(this);
		bRegistration.setOnClickListener(this);

		vSplash.setVisibility(View.VISIBLE);
	}

	@Override
	public void onClick(View v) {
		CustomLog.logI(TAG, "onClick");
		Intent intent = null;
		Integer id = v.getId();
		if (id == R.id.bLogin) {
			intent = new Intent(this, ActivityLogin.class);
		} else if (id == R.id.bRegistration) {
			intent = new Intent(this, ActivityRegistration.class);
		}
		startActivity(intent);
	}

}
